<script lang="tsx">
import { defineComponent, ref, onMounted, watch } from 'vue';
import { ElMessage, ElMessageBox, ElTable, ElTableColumn, ElInput, ElSelect, ElOption, ElUpload, ElDialog } from 'element-plus';
import { Trash2, ChevronDown, ChevronRight, Pencil, Plus, Save, X } from '@vben/icons';
import { addTeamMemberApi, getTeamInfoAndMembersListApi, deleteTeamMemberApi, updateTeamMemberApi, type AddTeamMemberInfo, type UpdateTeamMemberInfo, type TeamMemberInfo } from '#/api/competition/registration-info';
import { obsUpload } from '#/utils/obs';
import ObsImage from '#/components/obsImage.vue';
import type { TeamInfo } from './team-list.vue';

// 队员角色枚举
export enum TeamMemberRole {
  LEADER = '1', // 队长
  VICE_LEADER = '2', // 副队长
  MEMBER = '3' // 队员
}

// 角色映射对象
export const RoleMap = {
  [TeamMemberRole.LEADER]: '队长',
  [TeamMemberRole.VICE_LEADER]: '副队长',
  [TeamMemberRole.MEMBER]: '队员'
} as const;

// 角色选项数组
export const RoleOptions = [
  { label: '队长', value: TeamMemberRole.LEADER },
  { label: '副队长', value: TeamMemberRole.VICE_LEADER },
  { label: '队员', value: TeamMemberRole.MEMBER }
];

// 队员信息类型
export interface TeamMember {
  id: string;
  name: string;
  studentId: string; // 学号/工号，对应API的position字段
  phone: string;
  email: string;
  role: TeamMemberRole; // 使用枚举类型
  photoName: string; // 证件照片名称
  code: string; // 验证码
  editStatus: string;
  isEditing: boolean;
  isNewMember?: boolean; // 标识是否为新增成员
}

export default defineComponent({
  name: 'CollapsibleTeamPanel',
  props: {
    team: {
      type: Object as () => TeamInfo,
      required: true
    },
    isFirstTeam: {
      type: Boolean,
      default: false
    }
  },
  emits: ['edit-team', 'delete-team'],
  setup(props) {
    // 折叠状态
    const isExpanded = ref(props.isFirstTeam);

    // 队员列表数据
    const memberList = ref<TeamMember[]>([]);

    // 加载状态
    const loading = ref(false);

    // 是否显示团队提示
    const isShowTeamTips = ref(true);

    // 将API返回的TeamMemberInfo转换为组件使用的TeamMember
    const convertApiMemberToTeamMember = (apiMember: TeamMemberInfo): TeamMember => {
      return {
        id: apiMember.id,
        name: apiMember.name,
        studentId: apiMember.position,
        phone: apiMember.phone,
        email: apiMember.email,
        role: apiMember.role as TeamMemberRole,
        photoName: apiMember.photoName,
        code: '', // API返回中没有code字段，设为空
        editStatus: apiMember.photoName ? '查看证件' : '上传证件',
        isEditing: false,
        isNewMember: false // 从API获取的成员不是新成员
      };
    };

    // 获取团队成员数据
    const fetchTeamMembers = async (showLoading = true) => {
      if (!props.team.compId || !props.team.id) return;

      try {
        if (showLoading) {
          loading.value = true;
        }
        const response = await getTeamInfoAndMembersListApi({
          compId: props.team.compId,
          id: props.team.id, // 使用团队ID进行精确查询
          curPage: 1,
          pageSize: 100
        });

        // 由于传入了团队ID，返回的数据应该只包含指定团队
        const currentTeamData = response.data[0]; // 取第一个结果
        if (currentTeamData && currentTeamData.members) {
          memberList.value = currentTeamData.members.map(convertApiMemberToTeamMember);
        } else {
          // 如果没有成员数据，清空列表
          memberList.value = [];
        }
      } catch (error) {
        console.error('获取团队成员数据失败:', error);
      } finally {
        if (showLoading) {
          loading.value = false;
        }
      }
    };

    // 刷新当前团队成员数据（用于添加成员后的更新）
    const refreshTeamMembers = async () => {
      if (!isExpanded.value) return; // 只有展开状态才刷新
      await fetchTeamMembers(false); // 不显示loading，避免闪烁
    };



    // 切换折叠状态
    const toggleExpanded = async () => {
      isExpanded.value = !isExpanded.value;

      // 第一次展开时获取成员数据
      if (isExpanded.value && memberList.value.length === 0) {
        await fetchTeamMembers();
      }
    };

    // 监听团队变化，重新获取数据
    watch(() => props.team.id, () => {
      if (isExpanded.value) {
        fetchTeamMembers();
      }
    });

    // 组件挂载时，如果已展开则获取数据
    onMounted(() => {
      if (isExpanded.value) {
        fetchTeamMembers();
      }
    });



    // 证明/证件上传
    const proofUploadRef = ref();
    const currentUploadRow = ref<TeamMember | null>(null);
    const dialogVisible = ref(false);
    const imageUploadRef = ref<string>('');

    const beforeProofUpload = (file: File) => {
      const isImage = ['image/jpeg', 'image/png', 'image/jpg'].includes(file.type);
      const isLt10M = file.size / 1024 / 1024 < 10;
      if (!isImage) {
        ElMessage.error('只能上传 jpg、jpeg、png 格式的图片');
        return false;
      }
      if (!isLt10M) {
        ElMessage.error('上传文件大小不能超过 10MB');
        return false;
      }
      return true;
    };

    const handleProofUpload = async (options: any) => {
      const { file } = options;
      if (!currentUploadRow.value) return;
      try {
        await new Promise<void>((resolve, reject) => {
          obsUpload({
            Key: file.name,
            SourceFile: file,
            ContentType: file.type
          }, (err: any, _result: any, uploadedKey: string) => {
            if (err) {
              reject(err);
              return;
            }
            currentUploadRow.value!.photoName = uploadedKey;
            currentUploadRow.value!.editStatus = '查看证件';
            ElMessage.success('证件上传成功');
            resolve();
          });
        });
      } catch (error) {
        console.error('证件上传失败:', error);
      } finally {
        currentUploadRow.value = null;
      }
    };

    const openProofUpload = (row: TeamMember) => {
      currentUploadRow.value = row;
      const inputElement = proofUploadRef.value?.$el?.querySelector('input[type="file"]');
      if (inputElement) {
        inputElement.click();
      }
    };

    const handleProofCellClick = (row: TeamMember) => {
      if (row.photoName && typeof row.photoName === 'string') {
        imageUploadRef.value = row.photoName;
        dialogVisible.value = true;
        return;
      }
      openProofUpload(row);
    };

    const handleImageClose = () => {
      dialogVisible.value = false;
      imageUploadRef.value = '';
    };

    // 添加新队员
    const addMember = () => {
      // 根据当前队员数量确定默认角色
      let defaultRole: TeamMemberRole = TeamMemberRole.MEMBER;
      const currentMemberCount = memberList.value.length;

      if (currentMemberCount === 0) {
        defaultRole = TeamMemberRole.LEADER;
      } else if (currentMemberCount === 1) {
        defaultRole = TeamMemberRole.VICE_LEADER;
      }

      const newMember: TeamMember = {
        id: Date.now().toString(),
        name: '',
        studentId: '',
        phone: '',
        email: '',
        role: defaultRole,
        photoName: '',
        code: '',
        editStatus: '上传证件',
        isEditing: true,
        isNewMember: true // 标记为新增成员
      };
      memberList.value.push(newMember);
    };

    // 编辑单行
    const editMember = (member: TeamMember) => {
      member.isEditing = true;
    };

    // 保存单行
    const saveMember = async (member: TeamMember) => {
      try {
        // 验证必填字段
        if (!member.name.trim()) {
          ElMessage.error('请输入成员姓名');
          return;
        }
        if (!member.phone.trim()) {
          ElMessage.error('请输入联系方式');
          return;
        }
        if (!member.email.trim()) {
          ElMessage.error('请输入邮箱');
          return;
        }
        if (!member.studentId.trim()) {
          ElMessage.error('请输入职位');
          return;
        }
        if (!member.photoName.trim()) {
          ElMessage.error('请上传证明文件');
          return;
        }
        // 验证码为非必填字段，移除验证

        if (member.isNewMember) {
          // 新增成员
          const addMemberData: AddTeamMemberInfo = {
            id: member.id,
            teamId: props.team.id,
            name: member.name.trim(),
            role: member.role,
            phone: member.phone.trim(),
            email: member.email.trim(),
            position: member.studentId.trim(),
            photoName: member.photoName.trim(),
            code: member.code.trim()
          };

          await addTeamMemberApi(addMemberData);
          ElMessage.success('添加成员成功！');
        } else {
          // 修改成员
          const updateMemberData: UpdateTeamMemberInfo = {
            id: member.id,
            teamId: props.team.id,
            name: member.name.trim(),
            role: member.role,
            phone: member.phone.trim(),
            email: member.email.trim(),
            position: member.studentId.trim(),
            photoName: member.photoName.trim(),
            code: member.code.trim()
          };

          await updateTeamMemberApi(updateMemberData);
          ElMessage.success('修改成员成功！');
        }

        member.isEditing = false;
        member.isNewMember = false; // 保存后不再是新成员

        // 使用团队ID刷新成员数据
        await refreshTeamMembers();
      } catch (error) {
        console.error('保存队员失败:', error);
      }
    };

    // 删除队员
    const deleteMember = async (member: TeamMember) => {
      try {
        await ElMessageBox.confirm(
          `确定要删除队员"${member.name}"吗？`,
          '确认删除',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }
        );

        // 调用删除成员API
        await deleteTeamMemberApi(member.id);

        // 刷新成员数据
        await refreshTeamMembers();
        ElMessage.success('删除成员成功！');
      } catch (error) {
        // 用户取消删除或API调用失败（axios已有错误拦截提示）
      }
    };



    // 渲染团队头部信息
    const renderTeamHeader = () => (
      <div class="flex flex-col items-cente px-[24px] py-[16px]">
        {/* 管理提示 */}
        {isShowTeamTips.value && (
          <div class="w-full bg-blue-50 p-4 mb-6">
            <div class="flex items-start gap-3">
              <div class="w-[20px] h-[20px] rounded-full bg-blue-500 flex items-center justify-center text-white text-xs font-bold mt-0.5">
                i
              </div>
              <div class="flex-1">
                单个参赛团队不得多于5名队员；要求设置队长和副队长各一名（参与高校组赛事团队可报2名指导老师）；队长、副队长作为团队的主要联络人应确保联系方式真实有效，团队内每名成员均要求实名认证。
              </div>
              <X class="w-[16px] h-[16px] bg-[#AEAEAE] text-white rounded-full flex items-center justify-center cursor-pointer" onClick={() => isShowTeamTips.value = false} />
            </div>
          </div>
        )}
        <div class="w-full flex items-center">
          {/* 折叠图标 */}
          <div class="cursor-pointer" onClick={toggleExpanded}>
            {isExpanded.value ? <ChevronDown class="w-5 h-5" /> : <ChevronRight class="w-5 h-5" />}
          </div>

          {/* 团队信息 */}
          <div class="flex items-center ml-[8px]">
            <h3 class="font-[500]">{props.team.name}</h3>
          </div>
        </div>
      </div>
    );

    // 渲染队员管理区域
    const renderMemberManagement = () => (
      <div class="ml-[48px] mr-[24px] pb-[24px]">
        {/* 可编辑表格 */}
        <div class="editable-table-container">
          <ElTable
            data={memberList.value}
            border
            stripe
            size="small"
            style={{ width: '100%' }}
            v-loading={loading.value}
            element-loading-text="加载中..."
          >
            <ElTableColumn prop="role" label="成员身份" width="100" align="left">
              {{
                default: ({ row }: { row: TeamMember }) => (
                  row.isEditing ? (
                    <ElSelect v-model={row.role} placeholder="请选择" size="small">
                      {RoleOptions.map(option => (
                        <ElOption
                          key={option.value}
                          label={option.label}
                          value={option.value}
                        />
                      ))}
                    </ElSelect>
                  ) : (
                    <span>{RoleMap[row.role]}</span>
                  )
                )
              }}
            </ElTableColumn>

            <ElTableColumn prop="name" width="100" align="left">
              {{
                header: () => (
                  <span>
                    <span class="text-red-500 ml-1">*</span>
                    姓名
                  </span>
                ),
                default: ({ row }: { row: TeamMember }) => (
                  row.isEditing ? (
                    <ElInput v-model={row.name} placeholder="请输入" size="small" />
                  ) : (
                    <span>{row.name}</span>
                  )
                )
              }}
            </ElTableColumn>

            <ElTableColumn prop="phone" width="200" align="left">
              {{
                header: () => (
                  <span>
                    <span class="text-red-500 ml-1">*</span>
                    手机号码
                  </span>
                ),
                default: ({ row }: { row: TeamMember }) => (
                  row.isEditing ? (
                    <ElInput v-model={row.phone} placeholder="请输入" size="small" />
                  ) : (
                    <span>{row.phone}</span>
                  )
                )
              }}
            </ElTableColumn>

            <ElTableColumn prop="email" width="370" align="left">
              {{
                header: () => (
                  <span>
                    <span class="text-red-500 ml-1">*</span>
                    电子邮箱
                  </span>
                ),
                default: ({ row }: { row: TeamMember }) => (
                  row.isEditing ? (
                    <ElInput v-model={row.email} placeholder="请输入" size="small" />
                  ) : (
                    <span>{row.email}</span>
                  )
                )
              }}
            </ElTableColumn>

            <ElTableColumn prop="studentId" width="170" align="left">
              {{
                header: () => (
                  <span>
                    <span class="text-red-500 ml-1">*</span>
                    职位
                  </span>
                ),
                default: ({ row }: { row: TeamMember }) => (
                  row.isEditing ? (
                    <ElInput v-model={row.studentId} placeholder="请输入" size="small" />
                  ) : (
                    <span>{row.studentId}</span>
                  )
                )
              }}
            </ElTableColumn>

            <ElTableColumn prop="editStatus" width="100" align="left">
              {{
                header: () => (
                  <span>
                    <span class="text-red-500 ml-1">*</span>
                    证明证件
                  </span>
                ),
                default: ({ row }: { row: TeamMember }) => (
                  <span class="text-blue-500 cursor-pointer hover:underline" onClick={() => handleProofCellClick(row)}>{row.editStatus}</span>
                )
              }}
            </ElTableColumn>

            <ElTableColumn label="操作" width="76" align="left" fixed="right">
              {{
                default: ({ row }: { row: TeamMember }) => (
                  <div class="flex gap-[14px]">
                    {row.isEditing ? (
                      <el-tooltip content="保存" placement="top">
                        <Save class="w-[16px] h-[16px] cursor-pointer" onClick={() => saveMember(row)} />
                      </el-tooltip>
                    ) : (
                      <el-tooltip content="编辑" placement="top">
                        <Pencil class="w-[16px] h-[16px] cursor-pointer" onClick={() => editMember(row)} />
                      </el-tooltip>
                    )}
                    <el-tooltip content="删除" placement="top">
                      <Trash2 class="w-[16px] h-[16px] cursor-pointer" onClick={() => deleteMember(row)} />
                    </el-tooltip>
                  </div>
                )
              }}
            </ElTableColumn>
          </ElTable>
        </div>

        {/* 添加队员按钮放在表格下方 - 当成员数量达到5个时隐藏 */}
        {memberList.value.length < 5 && (
          <div class="bg-white border border-dashed border-[#DCDFE6] rounded-[4px] py-[13px] mt-[16px] text-center cursor-pointer" onClick={addMember}>
            <div class="flex items-center justify-center gap-2 text-sm font-medium">
              <Plus class="w-5 h-5" />
              <span>新增成员</span>
            </div>
          </div>
        )}
      </div>
    );



    return () => (
      <div class="border border-[#DCDFE6] rounded-[16px] bg-white overflow-hidden">
        {/* 团队头部 */}
        {renderTeamHeader()}

        {/* 队员管理区域（可折叠） */}
        {isExpanded.value && renderMemberManagement()}

        {/* 隐藏的证件上传控件 */}
        <ElUpload
          ref={proofUploadRef}
          class="hidden"
          accept=".jpg,.jpeg,.png"
          action="#"
          http-request={handleProofUpload}
          before-upload={beforeProofUpload}
          auto-upload={true}
          show-file-list={false}
          limit={1}
          style="display: none;"
        />

        {/* 查看证件预览弹窗 */}
        {dialogVisible.value && (
          <ElDialog
            v-model={dialogVisible.value}
            width="600px"
            align-center
            center
            destroy-on-close={true}
            title="查看证件"
            append-to-body={true}
            close-on-click-modal={false}
            before-close={handleImageClose}
          >
            <div class="min-h-[300px]">
              {imageUploadRef.value && (
                <ObsImage showPreview={false} src={imageUploadRef.value} />
              )}
            </div>
          </ElDialog>
        )}
      </div>
    );
  }
});
</script>

<style scoped>
.editable-table-container {
  border-radius: 8px;
  overflow: hidden;
}

.editable-table-container :deep(.el-table) {
  border-radius: 8px;
}

.editable-table-container :deep(.el-table th) {
  background-color: #f5f7fa;
  font-weight: 600;
  color: #303133;
}

.editable-table-container :deep(.el-table td) {
  padding: 8px 0;
}

.editable-table-container :deep(.el-input__wrapper) {
  padding: 4px 8px;
  border-radius: 4px;
}

.editable-table-container :deep(.el-select) {
  width: 100%;
}

.editable-table-container :deep(.el-button) {
  padding: 4px 8px;
  border-radius: 4px;
}
</style>
